var network = require('../utils/network_util.js');
var api = require('../utils/api.js');

// 查看优惠券详情
function couponDetails(target, e) {
  // var item = e.currentTarget.dataset.item;
  // var status = e.currentTarget.dataset.status;
  // // console.log(item)
  // if (target.data.name) {

  // } else {
  //   wx.navigateTo({
  //     url: '/pages/myself/coupon/couponDetails' + "?coupon=" + JSON.stringify(item) + '&myself=' + target.data.myself + '&status=' + status
  //   })
  // }
}

// 立即使用优惠券
function userCoupon(target, e) {
  var coupon = e.currentTarget.dataset.item;
  if (target.route == "pages/pay/chooseCoupon") {
    wx.navigateBack({
      delta: 1
    })
    //获取页面栈
    var pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2];
      if (prePage.getCoupon && typeof (prePage.getCoupon) == "function") {
        prePage.getCoupon(coupon);
      }
    }
  } else {
    wx.redirectTo({
      url: '/pages/product/Product'
    })
  }
}

// 领取优惠券
function receiveCoupon(target, e) {
  var item = e.currentTarget.dataset.item;
  var couponId = [];
  couponId.push(item.id);

  network._post_json(target, api.receiveCoupon, { couponId }, success);

}

// 获取优惠券列表结果
var success = function (that, res) {

  if (res.data.data == 0 || res.data.data == '领取成功！') {
    // wx.showToast({
    //   title: '已领完'
    // })
    // wx.redirectTo({
    //   url: '/pages/myself/coupon/tenantCoupon'
    // });
    that.onPullDownRefresh();
    //获取页面栈
    var pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2];
      if (prePage.refresh && typeof (prePage.refresh) == "function") {
        prePage.refresh();
      }
    }
    wx.showToast({
      title: '领取成功'
    })


  } else {
    that.showZanTopTips(1, '已领完');

  }

}

module.exports = {
  couponDetails: couponDetails,
  userCoupon: userCoupon,
  receiveCoupon: receiveCoupon
}
